// 文件上传逻辑
document.addEventListener('DOMContentLoaded', function() {
    const uploadArea = document.getElementById('upload-area');
    const fileInput = document.getElementById('file-input');
    const selectFileBtn = document.getElementById('select-file-btn');
    const fileList = document.getElementById('file-list');
    const fileItems = document.getElementById('file-items');
    const uploadBtn = document.getElementById('upload-btn');
    const resetBtn = document.getElementById('reset-btn');
    const uploadProgress = document.getElementById('upload-progress');
    const progressBar = document.getElementById('progress-bar');
    const progressText = document.getElementById('progress-text');
    const progressPercentage = document.getElementById('progress-percentage');
    const resultMessage = document.getElementById('result-message');

    let selectedFiles = [];

    // 点击上传区域触发文件选择
    uploadArea.addEventListener('click', () => {
        fileInput.click();
    });

    // 拖放文件处理
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('upload-hover');
    });

    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('upload-hover');
    });

    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('upload-hover');

        if (e.dataTransfer.files.length > 0) {
            handleFiles(e.dataTransfer.files);
        }
    });

    // 选择文件处理
    fileInput.addEventListener('change', () => {
        if (fileInput.files.length > 0) {
            handleFiles(fileInput.files);
        }
    });

    // 处理选中的文件
    function handleFiles(files) {
        selectedFiles = Array.from(files);
        renderFileList();
        uploadBtn.classList.remove('hidden');
        resetBtn.classList.remove('hidden');
    }

    // 渲染文件列表
    function renderFileList() {
        if (selectedFiles.length === 0) {
            fileList.classList.add('hidden');
            return;
        }

        fileList.classList.remove('hidden');
        fileItems.innerHTML = '';

        selectedFiles.forEach((file, index) => {
            const fileSize = formatFileSize(file.size);
            const fileType = getFileExtension(file.name);
            const fileItem = document.createElement('div');
            fileItem.className = 'flex items-center justify-between bg-gray-50 p-3 rounded-lg';
            fileItem.innerHTML = `
                        <div class="flex items-center">
                            <div class="w-10 h-10 bg-primary/10 rounded-md flex items-center justify-center mr-3">
                                <i class="fa fa-file-${getFileIcon(fileType)} text-primary"></i>
                            </div>
                            <div>
                                <p class="font-medium text-dark truncate max-w-xs">${file.name}</p>
                                <p class="text-dark/60 text-xs">${fileSize} - ${fileType.toUpperCase()} 文件</p>
                            </div>
                        </div>
                        <button class="remove-file text-red-500 hover:text-red-700 transition-custom" data-index="${index}">
                            <i class="fa fa-times"></i>
                        </button>
                    `;
            fileItems.appendChild(fileItem);
        });

        // 添加删除文件事件
        document.querySelectorAll('.remove-file').forEach(button => {
            button.addEventListener('click', (e) => {
                const index = parseInt(e.currentTarget.getAttribute('data-index'));
                selectedFiles.splice(index, 1);
                renderFileList();

                if (selectedFiles.length === 0) {
                    uploadBtn.classList.add('hidden');
                    resetBtn.classList.add('hidden');
                }
            });
        });
    }

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 获取文件扩展名
    function getFileExtension(filename) {
        return filename.split('.').pop().toLowerCase();
    }

    // 获取文件图标
    function getFileIcon(extension) {
        const icons = {
            pdf: 'pdf-o',
            doc: 'word-o',
            docx: 'word-o',
            txt: 'text-o',
            md: 'markdown-o',
            ppt: 'powerpoint-o',
            pptx: 'powerpoint-o',
            xls: 'excel-o',
            xlsx: 'excel-o',
            default: 'o'
        };
        return icons[extension] || icons.default;
    }

    // 上传文件
    uploadBtn.addEventListener('click', async () => {
        if (selectedFiles.length === 0) return;

        // 显示进度条
        uploadProgress.classList.remove('hidden');
        uploadBtn.disabled = true;

        // 隐藏之前的结果消息
        resultMessage.classList.add('hidden');

        // 依次上传每个文件
        for (let i = 0; i < selectedFiles.length; i++) {
            const file = selectedFiles[i];
            progressText.textContent = `正在上传 ${file.name} (${i+1}/${selectedFiles.length})`;

            try {
                await uploadFile(file, i, selectedFiles.length);
            } catch (error) {
                console.error('上传失败:', error);
                showResult('上传失败: ' + error.message, 'error');
                uploadBtn.disabled = false;
                return;
            }
        }

        // 全部上传完成
        progressBar.style.width = '100%';
        progressPercentage.textContent = '100%';
        progressText.textContent = '上传完成，正在处理...';

        // 显示成功消息
        setTimeout(() => {
            showResult(`成功上传并处理 ${selectedFiles.length} 个文件`, 'success');
            uploadBtn.disabled = false;
        }, 500);
    });

    // 上传单个文件
    async function uploadFile(file, index, total) {
        return new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append('file', file);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/rag/add', true);

            // 更新进度
            xhr.upload.addEventListener('progress', (e) => {
                if (e.lengthComputable) {
                    const percentComplete = ((e.loaded / e.total) / total + (index / total)) * 100;
                    progressBar.style.width = percentComplete + '%';
                    progressPercentage.textContent = Math.round(percentComplete) + '%';
                }
            });

            xhr.onload = () => {
                if (xhr.status === 200) {
                    resolve();
                } else {
                    reject(new Error(xhr.statusText));
                }
            };

            xhr.onerror = () => {
                reject(new Error('网络错误'));
            };

            xhr.send(formData);
        });
    }

    // 重置上传
    resetBtn.addEventListener('click', () => {
        selectedFiles = [];
        fileInput.value = '';
        renderFileList();
        uploadBtn.classList.add('hidden');
        resetBtn.classList.add('hidden');
        uploadProgress.classList.add('hidden');
        resultMessage.classList.add('hidden');
    });

    // 显示结果消息
    function showResult(message, type) {
        resultMessage.textContent = message;

        if (type === 'success') {
            resultMessage.className = 'bg-green-100 text-green-800 p-4 rounded-lg mb-6';
            resultMessage.innerHTML = `
                        <div class="flex items-center">
                            <i class="fa fa-check-circle text-green-500 mr-3 text-xl"></i>
                            <span>${message}</span>
                        </div>
                    `;
        } else if (type === 'error') {
            resultMessage.className = 'bg-red-100 text-red-800 p-4 rounded-lg mb-6';
            resultMessage.innerHTML = `
                        <div class="flex items-center">
                            <i class="fa fa-exclamation-circle text-red-500 mr-3 text-xl"></i>
                            <span>${message}</span>
                        </div>
                    `;
        }

        resultMessage.classList.remove('hidden');
    }
});